#!/bin/bash -e
# shellcheck disable=SC2034,SC2129
# shellcheck source=/dev/null

# Refs
# The Debian package management tools
# https://www.debian.org/doc/manuals/debian-faq/pkgtools.en.html

EXEC_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)

BASE_NAME="__BASE_NAME__"
INSTALLER_MODE="__INSTALLER_MODE__"
INSTALLER_VERSION=$(cat "${EXEC_DIR}/${BASE_NAME}-version.txt")

# Functions
if [ ! -f "${EXEC_DIR}/FUNCTIONS" ]; then
    # echo "Cannot found 'FUNCTIONS' file at [${EXEC_DIR}]"
    echo "无法在 [${EXEC_DIR}] 找到 'FUNCTIONS' 文件"
    exit 1
fi
source "${EXEC_DIR}/FUNCTIONS"

# echo "Installer Mode: ${INSTALLER_MODE}"
# echo "Installer Version: ${INSTALLER_VERSION}"
echo "安装模式: ${INSTALLER_MODE}"
echo "补丁包版本: ${INSTALLER_VERSION}"

# Get OS Information
OS_ARCH="$(GetOSArch)"
OS_VER="$(GetOSVersion)"
OS_MAINLINE="$(GetOSMainlineVersion)"
PATHES_DIR="$(GetPatchFolder "${OS_VER}" "${OS_MAINLINE}")"
# echo "System is ${OS_VER}${OS_MAINLINE:+ ${OS_MAINLINE}}, CPU is ${OS_ARCH}, Patch Dir: ${PATHES_DIR}"
echo "系统: ${OS_VER}${OS_MAINLINE:+ ${OS_MAINLINE}}, CPU: ${OS_ARCH}, 补丁目录: ${PATHES_DIR}"

# Custom Check
OS_DIST_ID="$(GetOSDistID)"
if [ -n "${OS_DIST_ID}" ]; then
    # echo "System dist id: ${OS_DIST_ID}"
    echo "系统 DIST_ID: ${OS_DIST_ID}"
    if [ "${OS_VER}" = "v10" ] && echo "${OS_DIST_ID}" | grep -v -q "Kylin-Desktop-V10-Release-CCB-21010818.Z1-arm64"; then
        # echo "Not match dist id, Exit"
        echo "不匹配的系统 DIST_ID, 退出！"
        exit 0
    fi
    if [ "${OS_VER}" = "v10sp1" ] && echo "${OS_DIST_ID}" | grep -v -q "Kylin-Desktop-V10-SP1-2203-General-Release-update3-CCB-COUNTER-20231110"; then
        # echo "Not match dist id, Exit"
        echo "不匹配的系统 DIST_ID, 退出！"
        exit 0
    fi
else
    # echo "Not match dist id, Exit"
    echo "不匹配的系统 DIST_ID, 退出！"
    exit 0
fi

# Generate Install List
Data_GenPatchInstallList "${PATHES_DIR}"

# Update Dependencies
Data_UpdateDepends

if [ "${INSTALLER_MODE}" = "GUI" ]; then
    # Generate Patch List Info Html
    Html_GenerateList
    # Show Changelog
    GUI_ShowHtml "${INSTALLER_MODE}" "${G_CHANGELOG_HTML}" "补丁说明"
    # Show Patch List
    GUI_ShowHtml "${INSTALLER_MODE}" "${G_INSTALL_LIST_HTML}" "补丁列表" "开始安装"
fi

# Install Patches
DEB_Installation "${INSTALLER_MODE}" "正在安装补丁" "准备补丁文件 ..."
